<template>
  <div class="job-list">
    <el-card>
      <template #header v-if="userStore.userInfo?.role !== 'student'">
        <div class="card-header">
          <div class="header-actions" >
            <el-button type="primary" @click="handleCreate">
              <el-icon><Plus /></el-icon>
              发布岗位
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <div class="search-form">
        <div class="search-form-header">
          <h3 class="search-title">
            <el-icon><Search /></el-icon>
            筛选条件
          </h3>
          <el-button
            text
            type="primary"
            @click="toggleSearchForm"
            class="toggle-btn"
          >
            {{ searchFormCollapsed ? '展开' : '收起' }}
            <el-icon class="toggle-icon" :class="{ 'is-collapsed': searchFormCollapsed }">
              <ArrowDown />
            </el-icon>
          </el-button>
        </div>

        <el-collapse-transition>
          <div v-show="!searchFormCollapsed" class="search-form-content">
            <el-form :model="searchForm" class="search-form-inner">
              <el-row :gutter="16">
                <el-col :xs="24" :sm="12" :md="8" :lg="6">
                  <el-form-item label="关键词搜索">
                    <el-input
                      v-model="searchForm.search"
                      placeholder="请输入公司名称、岗位名称"
                      clearable
                      prefix-icon="Search"
                      @keyup.enter="handleSearch"
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>

                <el-col :xs="24" :sm="12" :md="8" :lg="6">
                  <el-form-item label="工作性质">
                    <el-select
                      v-model="searchForm.job_type"
                      placeholder="请选择工作性质"
                      clearable
                      class="search-select"
                    >
                      <el-option label="全职" value="full_time" />
                      <el-option label="兼职" value="part_time" />
                      <el-option label="实习" value="internship" />
                      <el-option label="合同工" value="contract" />
                      <el-option label="远程工作" value="remote" />
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :xs="24" :sm="12" :md="8" :lg="6">
                  <el-form-item label="工作方式">
                    <el-select
                      v-model="searchForm.work_mode"
                      placeholder="请选择工作方式"
                      clearable
                      class="search-select"
                    >
                      <el-option label="线上" value="online" />
                      <el-option label="线下" value="offline" />
                      <el-option label="混合" value="hybrid" />
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :xs="24" :sm="12" :md="8" :lg="6">
                  <el-form-item label="学历要求">
                    <el-select
                      v-model="searchForm.education"
                      placeholder="请选择学历要求"
                      clearable
                      class="search-select"
                    >
                      <el-option label="不限" value="none" />
                      <el-option label="高中" value="high_school" />
                      <el-option label="大专" value="college" />
                      <el-option label="本科" value="bachelor" />
                      <el-option label="硕士" value="master" />
                      <el-option label="博士" value="phd" />
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :xs="24" :sm="12" :md="8" :lg="6" v-if="isStudent">
                  <el-form-item label="薪资范围">
                    <div class="salary-range">
                      <el-input
                        v-model="searchForm.salary_min"
                        placeholder="最低薪资"
                        type="number"
                        class="salary-input"
                      />
                      <span class="salary-separator">-</span>
                      <el-input
                        v-model="searchForm.salary_max"
                        placeholder="最高薪资"
                        type="number"
                        class="salary-input"
                      />
                    </div>
                  </el-form-item>
                </el-col>

                <el-col :xs="24" :sm="12" :md="8" :lg="6">
                  <el-form-item label="工作地点">
                    <el-input
                      v-model="searchForm.location"
                      placeholder="请输入工作地点"
                      clearable
                      prefix-icon="Location"
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>

                <el-col :xs="24" class="search-actions-col">
                  <el-form-item class="search-actions">
                    <el-button type="primary" @click="handleSearch" :loading="loading">
                      <el-icon><Search /></el-icon>
                      搜索
                    </el-button>
                    <el-button @click="handleReset">
                      <el-icon><RefreshLeft /></el-icon>
                      重置
                    </el-button>
                    <el-button @click="handleAdvancedSearch" v-if="isStudent">
                      <el-icon><Filter /></el-icon>
                      高级筛选
                    </el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-transition>
      </div>

      <!-- 岗位列表 -->
      <div class="job-list-content">
        <el-table
          :data="filteredJobList"
          v-loading="loading"
          stripe
          style="width: 100%"
          size="small"
        >
          <el-table-column prop="title" label="岗位名称" min-width="150" />
          <el-table-column label="公司名称" min-width="150">
            <template #default="{ row }">
              {{ row.company_info?.name || '未知公司' }}
            </template>
          </el-table-column>
          <el-table-column prop="work_location" label="工作地点" min-width="120" />
          <el-table-column label="工作性质" width="100">
            <template #default="{ row }">
              <el-tag :type="getJobTypeTagType(row.job_type)">
                {{ getJobTypeText(row.job_type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="工作方式" width="100">
            <template #default="{ row }">
              <el-tag :type="getWorkModeTagType(row.work_mode)">
                {{ getWorkModeText(row.work_mode) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="salary_range" label="薪资水平" width="120" />
          <el-table-column prop="education_requirement" label="学历要求" width="100" />
          <el-table-column prop="positions_available" label="招聘人数" width="80" />
          <el-table-column label="状态" width="100" v-if="userStore.userInfo?.role !== 'student'">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button size="small" @click="handleDetail(row)">查看详情</el-button>
              <template v-if="userStore.userInfo?.role === 'student'">
                <el-button
                  type="primary"
                  size="small"
                  @click="handleApply(row)"
                  :disabled="row.status !== 'published'"
                >
                  申请岗位
                </el-button>
              </template>
              <template v-else>
                <el-button size="small" @click="handleEdit(row)">编辑</el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(row)"
                  v-if="userStore.userInfo?.role === 'admin'"
                >
                  删除
                </el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 岗位申请对话框 -->
    <el-dialog
      v-model="applyDialogVisible"
      title="申请岗位"
      width="600px"
      @close="resetApplyForm"
    >
      <el-form :model="applyForm" :rules="applyRules" ref="applyFormRef" label-width="100px">
        <el-form-item label="岗位信息">
          <div class="job-info">
            <h4>{{ selectedJob?.title }}</h4>
            <p>{{ selectedJob?.company_info?.name || '未知公司' }} - {{ selectedJob?.work_location }}</p>
            <p>薪资：{{ selectedJob?.salary_range }}</p>
          </div>
        </el-form-item>
        <el-form-item label="求职信" prop="cover_letter">
          <el-input
            v-model="applyForm.cover_letter"
            type="textarea"
            :rows="4"
            placeholder="请简要介绍您的求职意向和优势..."
          />
        </el-form-item>
        <el-form-item label="简历文件">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :limit="1"
            accept=".pdf,.doc,.docx"
            :on-change="handleFileChange"
          >
            <el-button>选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                只能上传 PDF、DOC、DOCX 文件，且不超过 10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="applyDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitApplication" :loading="submitting">
          提交申请
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, ArrowDown, RefreshLeft, Filter, Location } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { jobApi, jobApplicationApi } from '@/api/jobs'
import type { Job } from '@/types'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const jobList = ref<Job[]>([])
const selectedJob = ref<Job | null>(null)
const applyDialogVisible = ref(false)
const applyFormRef = ref()
const uploadRef = ref()
const searchFormCollapsed = ref(false)

// 搜索表单
const searchForm = reactive({
  search: '',
  job_type: '',
  work_mode: '',
  education: '',
  location: '',
  salary_min: '',
  salary_max: ''
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 申请表单
const applyForm = reactive({
  cover_letter: '',
  resume_file: null as File | null
})

const applyRules = {
  cover_letter: [
    { required: true, message: '请填写求职信', trigger: 'blur' }
  ]
}

// 计算属性
const isStudent = computed(() => userStore.userInfo?.role === 'student')

// 过滤后的岗位列表 - 实现实时搜索
const filteredJobList = computed(() => {
  if (!jobList.value.length) return []

  return jobList.value.filter(job => {
    // 关键词搜索
    if (searchForm.search) {
      const searchText = searchForm.search.toLowerCase()
      const titleMatch = job.title?.toLowerCase().includes(searchText)
      const companyMatch = job.company_info?.name?.toLowerCase().includes(searchText)
      if (!titleMatch && !companyMatch) return false
    }

    // 工作性质筛选
    if (searchForm.job_type && job.job_type !== searchForm.job_type) {
      return false
    }

    // 工作方式筛选
    if (searchForm.work_mode && job.work_mode !== searchForm.work_mode) {
      return false
    }

    // 学历要求筛选
    if (searchForm.education && job.education_requirement !== searchForm.education) {
      return false
    }

    // 工作地点筛选
    if (searchForm.location) {
      const locationText = searchForm.location.toLowerCase()
      if (!job.work_location?.toLowerCase().includes(locationText)) {
        return false
      }
    }

    // 薪资范围筛选
    if (searchForm.salary_min || searchForm.salary_max) {
      const salaryRange = job.salary_range || ''
      const salaryNumbers = salaryRange.match(/\d+/g)
      if (salaryNumbers && salaryNumbers.length >= 2) {
        const minSalary = parseInt(salaryNumbers[0])
        const maxSalary = parseInt(salaryNumbers[1])

        if (searchForm.salary_min && maxSalary < parseInt(searchForm.salary_min)) {
          return false
        }
        if (searchForm.salary_max && minSalary > parseInt(searchForm.salary_max)) {
          return false
        }
      }
    }

    return true
  })
})

// 方法
const toggleSearchForm = () => {
  searchFormCollapsed.value = !searchFormCollapsed.value
}

const fetchJobList = async () => {
  loading.value = true
  try {
    const params: any = {
      page: pagination.page,
      page_size: pagination.pageSize,
      search: searchForm.search,
      job_type: searchForm.job_type,
      work_mode: searchForm.work_mode,
      education: searchForm.education,
      location: searchForm.location
    }

    // 处理薪资范围
    if (searchForm.salary_min) {
      params.salary_min = parseInt(searchForm.salary_min)
    }
    if (searchForm.salary_max) {
      params.salary_max = parseInt(searchForm.salary_max)
    }

    const response = await jobApi.getJobList(params)
    jobList.value = response.data.results || []
    pagination.total = response.data.count || 0
  } catch (error) {
    console.error('获取岗位列表失败:', error)
    ElMessage.error('获取岗位列表失败')
    jobList.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  fetchJobList()
}

const handleReset = () => {
  searchForm.search = ''
  searchForm.job_type = ''
  searchForm.work_mode = ''
  searchForm.education = ''
  searchForm.location = ''
  searchForm.salary_min = ''
  searchForm.salary_max = ''
  handleSearch()
}

const handleAdvancedSearch = () => {
  // 可以在这里实现更复杂的高级搜索功能
  ElMessage.info('高级筛选功能开发中...')
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchJobList()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchJobList()
}

const handleCreate = () => {
  router.push('/jobs/create')
}

const handleDetail = (job: Job) => {
  router.push(`/jobs/${job.id}/detail`)
}

const handleEdit = (job: Job) => {
  router.push(`/jobs/${job.id}/edit`)
}

const handleDelete = async (job: Job) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除岗位"${job.title}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await jobApi.deleteJob(job.id)
    ElMessage.success('删除成功')
    fetchJobList()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除岗位失败:', error)
      ElMessage.error('删除岗位失败')
    }
  }
}

const handleApply = (job: Job) => {
  selectedJob.value = job
  applyDialogVisible.value = true
}

const handleFileChange = (file: any) => {
  applyForm.resume_file = file.raw
}

const resetApplyForm = () => {
  applyForm.cover_letter = ''
  applyForm.resume_file = null
  selectedJob.value = null
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

const submitApplication = async () => {
  if (!applyFormRef.value) return

  try {
    await applyFormRef.value.validate()

    if (!selectedJob.value) {
      ElMessage.error('请选择要申请的岗位')
      return
    }

    submitting.value = true

    const formData = new FormData()
    formData.append('cover_letter', applyForm.cover_letter)
    if (applyForm.resume_file) {
      formData.append('resume_file', applyForm.resume_file)
    }

    await jobApi.applyJob(selectedJob.value.id, formData)

    ElMessage.success('申请提交成功')
    applyDialogVisible.value = false
    resetApplyForm()

  } catch (error) {
    console.error('提交申请失败:', error)
    ElMessage.error('提交申请失败')
  } finally {
    submitting.value = false
  }
}

// 辅助方法
const getJobTypeText = (type: string) => {
  const map: Record<string, string> = {
    full_time: '全职',
    part_time: '兼职',
    internship: '实习',
    contract: '合同工',
    remote: '远程工作'
  }
  return map[type] || type
}

const getJobTypeTagType = (type: string): 'primary' | 'success' | 'warning' | 'info' | 'danger' => {
  const map: Record<string, 'primary' | 'success' | 'warning' | 'info' | 'danger'> = {
    full_time: 'primary',
    part_time: 'success',
    internship: 'warning',
    contract: 'info',
    remote: 'danger'
  }
  return map[type] || 'info'
}

const getWorkModeText = (mode: string) => {
  const map: Record<string, string> = {
    online: '线上',
    offline: '线下',
    hybrid: '混合'
  }
  return map[mode] || mode
}

const getWorkModeTagType = (mode: string): 'primary' | 'success' | 'warning' | 'info' | 'danger' => {
  const map: Record<string, 'primary' | 'success' | 'warning' | 'info' | 'danger'> = {
    online: 'primary',
    offline: 'success',
    hybrid: 'warning'
  }
  return map[mode] || 'info'
}

const getStatusText = (status: string) => {
  const map: Record<string, string> = {
    draft: '草稿',
    published: '已发布',
    closed: '已关闭',
    expired: '已过期'
  }
  return map[status] || status
}

const getStatusTagType = (status: string): 'primary' | 'success' | 'warning' | 'info' | 'danger' => {
  const map: Record<string, 'primary' | 'success' | 'warning' | 'info' | 'danger'> = {
    draft: 'info',
    published: 'success',
    closed: 'warning',
    expired: 'danger'
  }
  return map[status] || 'info'
}

// 生命周期
onMounted(() => {
  fetchJobList()
})
</script>

<style lang="scss" scoped>

.job-list {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 18px;
      font-weight: 600;
    }
  }

  .search-form {
    margin-bottom: 12px;
    background: var(--bg-color-light);
    border: 1px solid var(--border-color-light);
    border-radius: 8px;
    overflow: hidden;
    transition: all 0.3s ease;

    .search-form-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 16px;
      background: var(--fill-color-light);
      border-bottom: 1px solid var(--border-color-extra-light);

      .search-title {
        margin: 0;
        font-size: 14px;
        font-weight: 600;
        color: var(--text-color-primary);
        display: flex;
        align-items: center;
        gap: 6px;

        .el-icon {
          color: var(--color-primary);
          font-size: 16px;
        }
      }

      .toggle-btn {
        display: flex;
        align-items: center;
        gap: 4px;
        color: var(--text-color-regular);
        font-size: 12px;
        padding: 4px 8px;

        .toggle-icon {
          transition: transform 0.3s ease;
          font-size: 12px;

          &.is-collapsed {
            transform: rotate(-90deg);
          }
        }
      }
    }

    .search-form-content {
      padding: 12px 16px;
    }

    .search-form-inner {
      .el-form-item {
        margin-bottom: 8px;

        :deep(.el-form-item__label) {
          color: var(--text-color-regular);
          font-weight: 500;
          font-size: 12px;
          line-height: 1.2;
          margin-bottom: 4px;
        }
      }

      .search-input,
      .search-select {
        :deep(.el-input) {
          --el-input-height: 28px;
        }

        :deep(.el-select) {
          --el-select-input-height: 28px;
        }
      }

      .salary-range {
        display: flex;
        align-items: center;
        gap: 6px;

        .salary-input {
          flex: 1;

          :deep(.el-input) {
            --el-input-height: 28px;
          }
        }

        .salary-separator {
          color: var(--text-color-secondary);
          font-size: 12px;
        }
      }

      .search-actions-col {
        margin-top: 4px;
      }

      .search-actions {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;

        .el-button {
          height: 28px;
          padding: 0 12px;
          font-size: 12px;
        }
      }
    }
  }


  .job-list-content {
    :deep(.el-table) {
      --el-table-row-height: 40px;
      --el-table-header-height: 36px;
      font-size: 13px;

      .el-table__header-wrapper {
        .el-table__header {
          th {
            padding: 6px 0;
            background: var(--fill-color-light);
          }
        }
      }

      .el-table__body-wrapper {
        .el-table__body {
          td {
            padding: 6px 0;
          }
        }
      }

      .el-button {
        height: 24px;
        padding: 0 8px;
        font-size: 12px;

        &.el-button--small {
          height: 24px;
          padding: 0 8px;
        }
      }

      .el-tag {
        height: 20px;
        line-height: 18px;
        font-size: 11px;
        padding: 0 6px;
      }
    }

    .pagination-wrapper {
      margin-top: 12px;
      display: flex;
      justify-content: center;

      :deep(.el-pagination) {
        --el-pagination-button-height: 28px;
        --el-pagination-button-width: 28px;
        font-size: 12px;

        .el-pagination__sizes {
          .el-select {
            --el-select-input-height: 28px;
          }
        }

        .el-pagination__jump {
          .el-input {
            --el-input-height: 28px;
          }
        }
      }
    }
  }

  .job-info {
    h4 {
      margin: 0 0 8px 0;
      color: #303133;
    }

    p {
      margin: 4px 0;
      color: #606266;
      font-size: 14px;
    }
  }
}
</style>